package com.baidu.dao;

import com.baidu.entity.GoodsBean;
import com.baidu.entity.SortBean;
import com.baidu.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.util.List;

/**
 * 创作时间：2019/9/20 14:20
 * 作者：李增强
 */
public class GoodsDao {
    JDBCUtils ju = new JDBCUtils();
    Connection conn = null;
    QueryRunner ru = new QueryRunner();
    public List<GoodsBean> getGoodsList(String ssql) {
        try {
            conn = ju.getConn();
            String sql= "select a.*,b.id sortid,b.name sname from t_goods a left join t_sort b on a.sortid=b.id where 1=1 ";
            sql+=ssql;
            sql+=" order by a.id desc";
            return ru.query(conn, sql, new BeanListHandler<GoodsBean>(GoodsBean.class));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
        return null;
    }

    public List<SortBean> getSortList() {
        try {
            conn = ju.getConn();
            String sql= "select b.id sortid,b.name sname from t_sort b";
            return ru.query(conn, sql, new BeanListHandler<SortBean>(SortBean.class));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
        return null;
    }

    public GoodsBean getGoodsById(String id) {
        try {
            conn = ju.getConn();
            String sql= "select a.*,b.id sortid,b.name sname from t_goods a left join t_sort b on a.sortid=b.id where a.id="+id;
            return ru.query(conn, sql, new BeanHandler<GoodsBean>(GoodsBean.class));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
        return null;
    }

    public boolean updateGoods(String buycount, String id) {
        try {
            conn = ju.getConn();
            String sql= "update t_goods set remaining = remaining-"+buycount+" where id="+id;
            return ru.update(conn, sql)==1;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ju.closeJDBC(conn);
        }
        return false;
    }
}
